/*================================================================
*   Copyright (C) 2020 Sangfor Ltd. All rights reserved.
*   
*   文件名称：test.cpp
*   创 建 者：Ann
*   创建日期：2020年05月17日
*   描    述：
*
================================================================*/

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0)
    {
        perror("socket");
        return 0;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(19999);
    addr.sin_addr.s_addr = inet_addr("172.16.99.129");

    bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));

    listen(sockfd, 5);

    //定义并且清空
    fd_set readfds;
    FD_ZERO(&readfds);
    //添加
    FD_SET(0, &readfds);
    FD_SET(sockfd, &readfds);

    //监控
    int ret = select(sockfd+1, &readfds, NULL, NULL, NULL);
    if(ret > 0)
    {
        if(FD_ISSET(0, &readfds))
        {
            char buf[1024] = {0};
            read(0, buf, sizeof(buf) - 1);
            printf("buf:%s\n", buf);

            //判断sockfd是否还在readfds里面
            printf("FD_ISSET(sockfd, &readfds) -- > ret = %d\n", FD_ISSET(sockfd, &readfds));
        }
        else if(FD_ISSET(sockfd, &readfds))
        {
            printf("FD_ISSET(fd, &readfds)\n");
            int newfd = accept(sockfd, NULL, NULL);
            printf("newfd: %d\n", newfd);

            printf("FD_ISSET(0, &readfds) -- > ret = %d\n", FD_ISSET(0, &readfds));
        }
    }



    FD_CLR(0, &readfds);
    FD_CLR(sockfd, &readfds);
    return 0;
}
